package com.api.controller;

import com.api.common.exception.MySystemException;
import com.api.common.utils.R;
import com.api.service.UploadService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.UUID;

import static com.api.common.utils.FileUtils.getFilePath;

/*
文件上传
 */
@RestController
@RequestMapping("/api")
@Tag(name = "文件上传")
public class UploadController {
    @Autowired
    private UploadService uploadService;
    @PostMapping("upload")
    @Operation(summary = "上传")
    public R getUpload(@RequestParam("file") MultipartFile file) throws IOException {
        //判断文件是否为空
        if (file.isEmpty()) {throw new MySystemException("文件不存在");}
        // 获取上传文件名
        String filename = file.getOriginalFilename();
        String suffixName = filename.substring(filename.lastIndexOf("."));
        //生成新的文件名称
        String newImgName = UUID.randomUUID() + suffixName;
        file.transferTo(new File(getFilePath() + File.separator + newImgName));
        HashMap<String, String> res = new HashMap<>();
        //文件路径
        res.put("file", "upload/" + newImgName);
        //带地址路径
        res.put("url",uploadService.toAbsoluteUrl(newImgName));
        return R.ok().put("data",res);
    }
}
